<template>
  <div class="wholesale-customer-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>批发客户管理</h2>
      <p>管理批发客户信息、资质认证、信用额度和价格等级</p>
    </div>

    <!-- 搜索和操作区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="客户名称">
          <el-input
            v-model="searchForm.customerName"
            placeholder="请输入客户名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="客户类型">
          <el-select v-model="searchForm.customerType" placeholder="请选择客户类型" clearable style="width: 150px">
            <el-option label="一级批发商" value="level1" />
            <el-option label="二级批发商" value="level2" />
            <el-option label="零售商" value="retailer" />
            <el-option label="连锁超市" value="chain" />
            <el-option label="电商平台" value="ecommerce" />
          </el-select>
        </el-form-item>
        <el-form-item label="信用等级">
          <el-select v-model="searchForm.creditLevel" placeholder="请选择信用等级" clearable style="width: 150px">
            <el-option label="AAA级" value="AAA" />
            <el-option label="AA级" value="AA" />
            <el-option label="A级" value="A" />
            <el-option label="B级" value="B" />
            <el-option label="C级" value="C" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="正常" value="active" />
            <el-option label="暂停" value="suspended" />
            <el-option label="黑名单" value="blacklist" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增客户
        </el-button>
        <el-button type="success" @click="handleBatchApprove" :disabled="!selectedCustomers.length">
          <el-icon><Check /></el-icon>
          批量审核
        </el-button>
        <el-button type="warning" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
        <el-button type="info" @click="handleImport">
          <el-icon><Upload /></el-icon>
          导入客户
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="filteredCustomers"
        border
        stripe
        v-loading="loading"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="customerCode" label="客户编码" width="120" />
        <el-table-column prop="customerName" label="客户名称" width="200" show-overflow-tooltip />
        <el-table-column prop="customerType" label="客户类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getCustomerTypeTagType(row.customerType)">{{ getCustomerTypeText(row.customerType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="contactPerson" label="联系人" width="100" />
        <el-table-column prop="contactPhone" label="联系电话" width="130" />
        <el-table-column prop="creditLevel" label="信用等级" width="100">
          <template #default="{ row }">
            <el-tag :type="getCreditLevelTagType(row.creditLevel)">{{ row.creditLevel }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creditLimit" label="信用额度" width="120">
          <template #default="{ row }">
            <span class="amount">¥{{ row.creditLimit?.toLocaleString() || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="usedCredit" label="已用额度" width="120">
          <template #default="{ row }">
            <span class="amount">¥{{ row.usedCredit?.toLocaleString() || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="priceLevel" label="价格等级" width="100">
          <template #default="{ row }">
            <el-tag type="info">{{ row.priceLevel }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button type="success" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-dropdown @command="(command) => handleDropdownCommand(command, row)">
              <el-button type="info" size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="credit">信用管理</el-dropdown-item>
                  <el-dropdown-item command="price">价格设置</el-dropdown-item>
                  <el-dropdown-item command="orders">订单记录</el-dropdown-item>
                  <el-dropdown-item command="suspend" v-if="row.status === 'active'">暂停合作</el-dropdown-item>
                  <el-dropdown-item command="activate" v-if="row.status === 'suspended'">恢复合作</el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 客户详情对话框 -->
    <el-dialog
      v-model="customerDialog.visible"
      :title="customerDialog.title"
      width="80%"
      :close-on-click-modal="false"
    >
      <CustomerForm
        v-if="customerDialog.visible"
        :customer-data="customerDialog.data"
        :mode="customerDialog.mode"
        @save="handleSaveCustomer"
        @cancel="handleCancelCustomer"
      />
    </el-dialog>

    <!-- 信用管理对话框 -->
    <el-dialog
      v-model="creditDialog.visible"
      title="信用额度管理"
      width="600px"
      :close-on-click-modal="false"
    >
      <div v-if="creditDialog.visible" class="credit-management">
        <p>信用管理功能开发中...</p>
        <div class="dialog-footer">
          <el-button @click="creditDialog.visible = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 价格设置对话框 -->
    <el-dialog
      v-model="priceDialog.visible"
      title="客户价格设置"
      width="70%"
      :close-on-click-modal="false"
    >
      <PriceForm
        v-if="priceDialog.visible"
        :customer-data="priceDialog.data"
        @save="handleSavePriceManagement"
        @cancel="priceDialog.visible = false"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Check,
  Download,
  Upload,
  View,
  Edit,
  ArrowDown
} from '@element-plus/icons-vue'
import CustomerForm from './components/CustomerForm.vue'
import PriceForm from './components/PriceForm.vue'

// 响应式数据
const loading = ref(false)
const selectedCustomers = ref([])

// 搜索表单
const searchForm = reactive({
  customerName: '',
  customerType: '',
  creditLevel: '',
  status: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 对话框状态
const customerDialog = reactive({
  visible: false,
  title: '',
  mode: 'add',
  data: null
})

const creditDialog = reactive({
  visible: false,
  data: null
})

const priceDialog = reactive({
  visible: false,
  data: null
})

// 模拟客户数据
const customers = ref([
  {
    id: 1,
    customerCode: 'WS001',
    customerName: '华润万家',
    customerType: 'chain',
    contactPerson: '张经理',
    contactPhone: '13800138001',
    email: 'zhang@crv.com.cn',
    address: '深圳市南山区华润城',
    creditLevel: 'AAA',
    creditLimit: 5000000,
    usedCredit: 2800000,
    priceLevel: 'VIP',
    status: 'active',
    createTime: '2024-01-15 09:30:00',
    businessLicense: 'BL2024001',
    taxNumber: 'TX2024001'
  },
  {
    id: 2,
    customerCode: 'WS002',
    customerName: '沃尔玛中国',
    customerType: 'chain',
    contactPerson: '李总监',
    contactPhone: '13800138002',
    email: 'li@walmart.com.cn',
    address: '北京市朝阳区沃尔玛总部',
    creditLevel: 'AAA',
    creditLimit: 8000000,
    usedCredit: 4200000,
    priceLevel: 'VIP',
    status: 'active',
    createTime: '2024-01-20 14:20:00',
    businessLicense: 'BL2024002',
    taxNumber: 'TX2024002'
  },
  {
    id: 3,
    customerCode: 'WS003',
    customerName: '家乐福',
    customerType: 'chain',
    contactPerson: '王主管',
    contactPhone: '13800138003',
    email: 'wang@carrefour.com.cn',
    address: '上海市浦东新区家乐福中国总部',
    creditLevel: 'AA',
    creditLimit: 3000000,
    usedCredit: 1500000,
    priceLevel: '一级',
    status: 'active',
    createTime: '2024-02-01 10:15:00',
    businessLicense: 'BL2024003',
    taxNumber: 'TX2024003'
  },
  {
    id: 4,
    customerCode: 'WS004',
    customerName: '大润发',
    customerType: 'level1',
    contactPerson: '赵经理',
    contactPhone: '13800138004',
    email: 'zhao@rt-mart.com.cn',
    address: '江苏省南京市大润发总部',
    creditLevel: 'AA',
    creditLimit: 2500000,
    usedCredit: 1200000,
    priceLevel: '一级',
    status: 'active',
    createTime: '2024-02-10 16:45:00',
    businessLicense: 'BL2024004',
    taxNumber: 'TX2024004'
  },
  {
    id: 5,
    customerCode: 'WS005',
    customerName: '永辉超市',
    customerType: 'chain',
    contactPerson: '孙总',
    contactPhone: '13800138005',
    email: 'sun@yonghui.com.cn',
    address: '福建省福州市永辉总部',
    creditLevel: 'A',
    creditLimit: 2000000,
    usedCredit: 800000,
    priceLevel: '二级',
    status: 'active',
    createTime: '2024-02-15 11:30:00',
    businessLicense: 'BL2024005',
    taxNumber: 'TX2024005'
  },
  {
    id: 6,
    customerCode: 'WS006',
    customerName: '美宜佳便利店',
    customerType: 'retailer',
    contactPerson: '陈店长',
    contactPhone: '13800138006',
    email: 'chen@meiyijia.com',
    address: '广东省东莞市美宜佳总部',
    creditLevel: 'B',
    creditLimit: 500000,
    usedCredit: 200000,
    priceLevel: '三级',
    status: 'suspended',
    createTime: '2024-02-20 13:20:00',
    businessLicense: 'BL2024006',
    taxNumber: 'TX2024006'
  },
  {
    id: 7,
    customerCode: 'WS007',
    customerName: '天猫超市',
    customerType: 'ecommerce',
    contactPerson: '刘运营',
    contactPhone: '13800138007',
    email: 'liu@tmall.com',
    address: '浙江省杭州市阿里巴巴园区',
    creditLevel: 'AAA',
    creditLimit: 10000000,
    usedCredit: 6500000,
    priceLevel: 'VIP',
    status: 'active',
    createTime: '2024-03-01 09:00:00',
    businessLicense: 'BL2024007',
    taxNumber: 'TX2024007'
  },
  {
    id: 8,
    customerCode: 'WS008',
    customerName: '京东超市',
    customerType: 'ecommerce',
    contactPerson: '周采购',
    contactPhone: '13800138008',
    email: 'zhou@jd.com',
    address: '北京市大兴区京东总部',
    creditLevel: 'AAA',
    creditLimit: 8000000,
    usedCredit: 4800000,
    priceLevel: 'VIP',
    status: 'active',
    createTime: '2024-03-05 15:30:00',
    businessLicense: 'BL2024008',
    taxNumber: 'TX2024008'
  }
])

// 计算属性
const filteredCustomers = computed(() => {
  let filtered = customers.value
  
  if (searchForm.customerName) {
    filtered = filtered.filter(customer => 
      customer.customerName.toLowerCase().includes(searchForm.customerName.toLowerCase())
    )
  }
  
  if (searchForm.customerType) {
    filtered = filtered.filter(customer => customer.customerType === searchForm.customerType)
  }
  
  if (searchForm.creditLevel) {
    filtered = filtered.filter(customer => customer.creditLevel === searchForm.creditLevel)
  }
  
  if (searchForm.status) {
    filtered = filtered.filter(customer => customer.status === searchForm.status)
  }
  
  pagination.total = filtered.length
  
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return filtered.slice(start, end)
})

// 方法
const getCustomerTypeText = (type) => {
  const typeMap = {
    level1: '一级批发商',
    level2: '二级批发商',
    retailer: '零售商',
    chain: '连锁超市',
    ecommerce: '电商平台'
  }
  return typeMap[type] || type
}

const getCustomerTypeTagType = (type) => {
  const typeMap = {
    level1: 'success',
    level2: 'primary',
    retailer: 'info',
    chain: 'warning',
    ecommerce: 'danger'
  }
  return typeMap[type] || 'info'
}

const getCreditLevelTagType = (level) => {
  const levelMap = {
    AAA: 'success',
    AA: 'primary',
    A: 'warning',
    B: 'info',
    C: 'danger'
  }
  return levelMap[level] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    active: '正常',
    suspended: '暂停',
    blacklist: '黑名单'
  }
  return statusMap[status] || status
}

const getStatusTagType = (status) => {
  const statusMap = {
    active: 'success',
    suspended: 'warning',
    blacklist: 'danger'
  }
  return statusMap[status] || 'info'
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    customerName: '',
    customerType: '',
    creditLevel: '',
    status: ''
  })
  pagination.currentPage = 1
  loadData()
}

const handleAdd = () => {
  customerDialog.visible = true
  customerDialog.title = '新增客户'
  customerDialog.mode = 'add'
  customerDialog.data = null
}

const handleView = (row) => {
  customerDialog.visible = true
  customerDialog.title = '查看客户'
  customerDialog.mode = 'view'
  customerDialog.data = { ...row }
}

const handleEdit = (row) => {
  customerDialog.visible = true
  customerDialog.title = '编辑客户'
  customerDialog.mode = 'edit'
  customerDialog.data = { ...row }
}

const handleDropdownCommand = (command, row) => {
  switch (command) {
    case 'credit':
      creditDialog.visible = true
      creditDialog.data = { ...row }
      break
    case 'price':
      priceDialog.visible = true
      priceDialog.data = { ...row }
      break
    case 'orders':
      ElMessage.info('跳转到订单记录页面')
      break
    case 'suspend':
      handleSuspendCustomer(row)
      break
    case 'activate':
      handleActivateCustomer(row)
      break
    case 'delete':
      handleDeleteCustomer(row)
      break
  }
}

const handleSuspendCustomer = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要暂停与客户 "${row.customerName}" 的合作吗？`,
      '暂停合作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    row.status = 'suspended'
    ElMessage.success('客户已暂停合作')
  } catch {
    // 用户取消操作
  }
}

const handleActivateCustomer = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要恢复与客户 "${row.customerName}" 的合作吗？`,
      '恢复合作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }
    )
    
    row.status = 'active'
    ElMessage.success('客户合作已恢复')
  } catch {
    // 用户取消操作
  }
}

const handleDeleteCustomer = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除客户 "${row.customerName}" 吗？此操作不可恢复！`,
      '删除客户',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    const index = customers.value.findIndex(customer => customer.id === row.id)
    if (index > -1) {
      customers.value.splice(index, 1)
      ElMessage.success('客户删除成功')
    }
  } catch {
    // 用户取消操作
  }
}

const handleBatchApprove = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要批量审核选中的 ${selectedCustomers.value.length} 个客户吗？`,
      '批量审核',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    selectedCustomers.value.forEach(customer => {
      if (customer.status === 'suspended') {
        customer.status = 'active'
      }
    })
    
    ElMessage.success('批量审核完成')
    selectedCustomers.value = []
  } catch {
    // 用户取消操作
  }
}

const handleExport = () => {
  ElMessage.success('导出功能开发中...')
}

const handleImport = () => {
  ElMessage.success('导入功能开发中...')
}

const handleSelectionChange = (selection) => {
  selectedCustomers.value = selection
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

const handleSaveCustomer = (customerData) => {
  if (customerDialog.mode === 'add') {
    const newCustomer = {
      ...customerData,
      id: Date.now(),
      customerCode: `WS${String(customers.value.length + 1).padStart(3, '0')}`,
      createTime: new Date().toLocaleString('zh-CN')
    }
    customers.value.unshift(newCustomer)
    ElMessage.success('客户创建成功')
  } else if (customerDialog.mode === 'edit') {
    const index = customers.value.findIndex(customer => customer.id === customerData.id)
    if (index > -1) {
      customers.value[index] = { ...customerData }
      ElMessage.success('客户更新成功')
    }
  }
  
  customerDialog.visible = false
}

const handleCancelCustomer = () => {
  customerDialog.visible = false
}

const handleSaveCreditManagement = (creditData) => {
  const index = customers.value.findIndex(customer => customer.id === creditData.id)
  if (index > -1) {
    customers.value[index].creditLimit = creditData.creditLimit
    customers.value[index].creditLevel = creditData.creditLevel
    ElMessage.success('信用额度更新成功')
  }
  creditDialog.visible = false
}

const handleSavePriceManagement = (priceData) => {
  const index = customers.value.findIndex(customer => customer.id === priceData.id)
  if (index > -1) {
    customers.value[index].priceLevel = priceData.priceLevel
    ElMessage.success('价格等级更新成功')
  }
  priceDialog.visible = false
}

const loadData = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    loading.value = false
  }, 500)
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.wholesale-customer-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 16px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.table-card {
  min-height: 400px;
}

.amount {
  color: #E6A23C;
  font-weight: 600;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .wholesale-customer-management {
    padding: 10px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 12px;
  }
  
  .action-buttons {
    flex-wrap: wrap;
  }
  
  .pagination-container {
    overflow-x: auto;
  }
}
</style>